package mspbots.next.ticket.core.grader.interceptor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import mspbots.next.ticket.core.grader.AbstractGradeRuleAdapter;
import mspbots.next.ticket.core.grader.GradeRuleInterceptorRegistration;
import mspbots.next.ticket.core.points.PointResult;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;


@Log4j2
@Service(value = "TICKET_SUMMARY_POINT_RULE")
public class TicketSummaryRuleInterceptor extends AbstractGradeRuleAdapter {

    private static final String RULE_KEY = "TicketSummary";
    private List<TicketSummaryParam> params;

    @Override
    public Mono<GradeRuleInterceptorRegistration> prepare(GradeRuleInterceptorRegistration gradeRuleInterceptorRegistration) {
        return Flux.just()
                .doFinally(r -> this.params = super.objectMapper
                        .convertValue(gradeRuleInterceptorRegistration.getRule().getParams(), new TypeReference<>() {
                        }))
                .then(Mono.just(gradeRuleInterceptorRegistration));
    }

    @Override
    public Mono<PointResult> scoring(JsonNode ticket) {
        String summary = super.getStringValue(ticket.get("summary"));
        int order = params.parallelStream()
                .filter(item -> item.isSelected() && StringUtils.hasLength(summary)
                        && StringUtils.hasLength(item.getSummaryKeyword()))
                .filter(item -> summary.toLowerCase().contains(item.getSummaryKeyword().toLowerCase()))
                .mapToInt(TicketSummaryParam::getPoints).sum();

        return Mono.just(PointResult.withDefault().point(order)
                .detail(PointResult.Detail.with(order, Map.of("summary", summary), RULE_KEY)));
    }

    @Data
    static class TicketSummaryParam {
        private Integer index;
        private Integer points;
        private String summaryKeyword;
        private boolean selected;
    }
}
